package com.github.common.extend.demo.util.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * 分片加载执行
 * 避免一次性加载大量数据
 * @author wangjj7
 * @date 2023/9/7
 * @description
 */
public class PartitionFlushReadListener<T> implements ReadListener<T> {

    private final int maxPartitionSize;

    private final List<T> cache;

    private final Consumer<List<T>> flushConsumer;

    public PartitionFlushReadListener(int partitionSize , Consumer<List<T>> flushConsumer){
        if (partitionSize <= 0){
            throw new IllegalArgumentException();
        }
        this.maxPartitionSize = partitionSize;
        this.cache = new ArrayList<>(partitionSize + 1);
        this.flushConsumer = flushConsumer;
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        if (flushConsumer == null){
            return;
        }
        if (cache.size() >= maxPartitionSize){
            flushConsumer.accept(cache);
            cache.clear();
        }
        cache.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (flushConsumer != null){
            flushConsumer.accept(cache);
            cache.clear();
        }
    }
}
